<template>
  <div class="site-setting-page page-view">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <div class="list">
        <div class="home-icon">
          <i class="iconfont icon-home"></i>
        </div>
        <div class="item">
          <router-link to="/">
            <span class="text">首页</span>
          </router-link>
        </div>
        <div class="seperate">
          <i class="iconfont icon-arrow-right-thin"></i>
        </div>
        <div class="item">
          <span class="text">网站设置</span>
        </div>
      </div>
      <h1 class="page-title">网站设置</h1>
    </div>

    <!-- Tab切换栏 -->
    <div class="tab-container">
      <div class="tabs">
        <div
          class="tab-item"
          :class="{ active: activeTab === 'basic' }"
          @click="switchTab('basic')"
        >
          基本设置
        </div>
        <div
          class="tab-item"
          :class="{ active: activeTab === 'text' }"
          @click="switchTab('text')"
        >
          文字设置
        </div>
      </div>
      <div class="tab-indicator" :style="indicatorStyle"></div>
    </div>

    <!-- 表单内容 -->
    <div class="form-container">
      <form class="v-form" @submit.prevent="submitForm">
        <!-- 基本设置 -->
        <div v-show="activeTab === 'basic'">
          <!-- 基本信息卡片 -->
          <div class="v-card">
            <div class="card-header">
              <h3>基本信息</h3>
            </div>
            <div class="card-body">
              <div class="form-grid">
                <!-- 网站名称 -->
                <div class="form-group">
                  <label class="form-label">网站名称</label>
                  <input
                    v-model="formData.site_name"
                    type="text"
                    class="form-input"
                    placeholder="请输入网站名称"
                    required
                  />
                </div>

                <!-- 公司名称 -->
                <div class="form-group">
                  <label class="form-label">公司名称</label>
                  <input
                    v-model="formData.company_name"
                    type="text"
                    class="form-input"
                    placeholder="请输入公司名称"
                    required
                  />
                </div>

                <!-- 公司地址 -->
                <div class="form-group">
                  <label class="form-label">公司地址</label>
                  <input
                    v-model="formData.address"
                    type="text"
                    class="form-input"
                    placeholder="请输入公司地址"
                    required
                  />
                </div>

                <!-- 客服电话 -->
                <div class="form-group">
                  <label class="form-label">客服电话</label>
                  <input
                    v-model="formData.service_phone"
                    type="text"
                    class="form-input"
                    placeholder="请输入客服电话"
                    required
                  />
                </div>

                <!-- 服务时间 -->
                <div class="form-group">
                  <label class="form-label">服务时间</label>
                  <input
                    v-model="formData.service_time"
                    type="text"
                    class="form-input"
                    placeholder="请输入服务时间"
                    required
                  />
                </div>

                <!-- 联系电话 -->
                <div class="form-group">
                  <label class="form-label">联系电话</label>
                  <input
                    v-model="formData.telephone"
                    type="text"
                    class="form-input"
                    placeholder="请输入联系电话"
                    required
                  />
                </div>

                <!-- 邮政编码 -->
                <div class="form-group">
                  <label class="form-label">邮政编码</label>
                  <input
                    v-model="formData.postcode"
                    type="text"
                    class="form-input"
                    placeholder="请输入邮政编码"
                    required
                  />
                </div>

                <!-- ICP备案信息 -->
                <div class="form-group">
                  <label class="form-label">ICP备案信息</label>
                  <input
                    v-model="formData.icp_info"
                    type="text"
                    class="form-input"
                    placeholder="请输入ICP备案信息"
                    required
                  />
                </div>

                <!-- 版权信息 -->
                <div class="form-group">
                  <label class="form-label">版权信息</label>
                  <input
                    v-model="formData.copyright"
                    type="text"
                    class="form-input"
                    placeholder="请输入版权信息"
                    required
                  />
                </div>
              </div>
            </div>
          </div>

          <!-- 二维码信息卡片 -->
          <div class="v-card">
            <div class="card-header">
              <h3>二维码信息</h3>
            </div>
            <div class="card-body">
              <div class="form-grid">
                <!-- 微信公众号二维码 -->
                <div class="form-group">
                  <label class="form-label">微信公众号二维码</label>
                  <ImgUploader
                    v-model="formData.wechat_qrcode"
                    :max-size="2"
                    accept="image/*"
                  />
                  <div class="form-hint">建议尺寸：200x200，大小不超过2MB</div>
                </div>

                <!-- 小程序二维码 -->
                <div class="form-group">
                  <label class="form-label">小程序二维码</label>
                  <ImgUploader
                    v-model="formData.mini_program_qrcode"
                    :max-size="2"
                    accept="image/*"
                  />
                  <div class="form-hint">建议尺寸：200x200，大小不超过2MB</div>
                </div>
                <div class="form-group">
                  <label class="form-label">小红书二维码</label>
                  <ImgUploader
                    v-model="formData.redbook_qrcode"
                    :max-size="2"
                    accept="image/*"
                  />
                  <div class="form-hint">建议尺寸：200x200，大小不超过2MB</div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 文字设置 -->
        <div v-if="activeTab === 'text'">
          <div class="v-card">
            <div class="card-header">
              <h3>文字内容设置</h3>
            </div>
            <div class="card-body">
              <div class="text-form-grid">
                <!-- 首页窗膜介绍 -->
                <div class="form-group">
                  <label class="form-label">首页窗膜介绍</label>
                  <textarea
                    v-model="formData.window_intro"
                    class="form-textarea"
                    placeholder="请输入首页窗膜介绍内容"
                  ></textarea>
                </div>

                <!-- 首页漆膜介绍 -->
                <div class="form-group">
                  <label class="form-label">首页漆膜介绍</label>
                  <textarea
                    v-model="formData.paint_intro"
                    class="form-textarea"
                    placeholder="请输入首页漆膜介绍内容"
                  ></textarea>
                </div>

                <!-- 首页建筑膜介绍 -->
                <div class="form-group">
                  <label class="form-label">首页建筑膜介绍</label>
                  <textarea
                    v-model="formData.building_intro"
                    class="form-textarea"
                    placeholder="请输入首页建筑膜介绍内容"
                  ></textarea>
                </div>

                <!-- 首页家具膜介绍 -->
                <div class="form-group">
                  <label class="form-label">首页家具膜介绍</label>
                  <textarea
                    v-model="formData.home_intro"
                    class="form-textarea"
                    placeholder="请输入首页家具膜介绍内容"
                  ></textarea>
                </div>

                <!-- 关于我们 -->
                <div class="form-group full-width">
                  <label class="form-label">关于我们</label>
                  <div id="about-us-editor" style="height: 300px;"></div>
                </div>

                <!-- 发展历史图片 -->
                <div class="form-group full-width">
                  <label class="form-label">发展历史图片</label>
                  <ImgUploader
                    v-model="formData.about_history"
                    :max-size="5"
                    accept="image/*"
                  />
                  <div class="form-hint">建议尺寸：1200x800，大小不超过5MB</div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 表单操作按钮 -->
        <div class="form-actions">
          <button type="submit" class="v-button primary">保存设置</button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch, onUnmounted } from "vue";
import { get, post } from "@/utils/request";
import { vToast } from "@/plugins/vToast";
import ImgUploader from "@/components/ImageUploader.vue";
import E from "wangeditor";

// 表单数据
const formData = ref({
  site_name: "",
  company_name: "",
  address: "",
  service_phone: "",
  service_time: "",
  telephone: "",
  postcode: "",
  wechat_qrcode: "",
  mini_program_qrcode: "",
  redbook_qrcode: "",
  icp_info: "",
  copyright: "",
  window_intro: "",
  paint_intro: "",
  building_intro: "",
  home_intro: "",
  about_us: "",
  about_history: ""
});

// Tab切换相关
const activeTab = ref("basic");
const tabItems = ref(["basic", "text"]);
const indicatorStyle = ref({});
const editorInstance = ref(null);
const editorReady = ref(false); // 新增编辑器就绪状态标识

// 监听about_us字段变化并更新编辑器内容
watch(() => formData.value.about_us, (newVal) => {
  if (editorInstance.value && editorReady.value) {
    editorInstance.value.txt.html(newVal);
  }
});

// 初始化Tab指示器位置
const updateIndicatorPosition = () => {
  nextTick(() => {
    const activeIndex = tabItems.value.indexOf(activeTab.value);
    const tabElements = document.querySelectorAll(".tab-item");
    if (tabElements[activeIndex]) {
      const { offsetLeft, offsetWidth } = tabElements[activeIndex];
      indicatorStyle.value = {
        transform: `translateX(${offsetLeft}px)`,
        width: `${offsetWidth}px`
      };
    }
  });
};

// 切换Tab
const switchTab = (tab) => {
  // 切换前销毁编辑器（如果存在）
  if (activeTab.value === 'text' && editorInstance.value) {
    editorInstance.value.destroy();
    editorInstance.value = null;
    editorReady.value = false;
  }
  
  activeTab.value = tab;
  updateIndicatorPosition();
  
  // 初始化富文本编辑器（切换到文字设置标签页时）
  if (tab === 'text') {
    initEditor();
  }
};

// 初始化富文本编辑器
const initEditor = () => {
  nextTick(() => {
    try {
      // 确保DOM元素存在
      const editorElement = document.getElementById('about-us-editor');
      if (!editorElement) {
        console.error('Editor container element not found');
        return;
      }
      
      // 创建编辑器实例
      editorInstance.value = new E('#about-us-editor');
      
      // 基础配置
      editorInstance.value.config.zIndex = 100;
      editorInstance.value.config.placeholder = "请输入关于我们的内容";
      
      // 菜单配置（精简常用功能）
      editorInstance.value.config.menus = [
        'head', 'bold', 'italic', 'underline', 'strikeThrough',
        'foreColor', 'backColor', 'link', 'list', 'justify',
        'quote', 'image', 'table', 'code', 'undo', 'redo'
      ];
      
      // 内容变化处理
      editorInstance.value.config.onchange = (html) => {
        formData.value.about_us = html;
      };
      
      // 创建编辑器
      editorInstance.value.create();
      
      // 设置初始内容
      editorInstance.value.txt.html(formData.value.about_us || '');
      
      // 标记编辑器已就绪
      editorReady.value = true;
    } catch (error) {
      console.error('富文本编辑器初始化失败:', error);
      vToast.error('富文本编辑器初始化失败');
    }
  });
};

// 获取网站设置
const fetchSettings = async () => {
  try {
    const res = await get("/setting/getAll");
    
    if (res.code === 200 && res.data) {
      formData.value = {
        ...formData.value,
        site_name: res.data.site_name || "",
        company_name: res.data.company_name || "",
        address: res.data.address || "",
        service_phone: res.data.service_phone || "",
        service_time: res.data.service_time || "",
        telephone: res.data.telephone || "",
        postcode: res.data.postcode || "",
        wechat_qrcode: res.data.wechat_qrcode || "",
        redbook_qrcode: res.data.redbook_qrcode || "",
        mini_program_qrcode: res.data.mini_program_qrcode || "",
        icp_info: res.data.icp_info || "",
        copyright: res.data.copyright || "",
        window_intro: res.data.window_intro || "",
        paint_intro: res.data.paint_intro || "",
        building_intro: res.data.building_intro || "",
        home_intro: res.data.home_intro || "",
        about_us: res.data.about_us || "",
        about_history: res.data.about_history || ""
      };
    } else {
      vToast.error(res.msg || "获取网站设置失败");
    }
  } catch (error) {
    vToast.error("获取网站设置失败");
    console.error(error);
  }
};

// 提交表单
const submitForm = async () => {
  try {
    // 验证逻辑
    if (activeTab.value === 'basic') {
      // 基本设置的验证
      if (!formData.value.site_name) {
        vToast.warning("请输入网站名称");
        return;
      }
      
      if (!formData.value.company_name) {
        vToast.warning("请输入公司名称");
        return;
      }
      
      if (!formData.value.service_phone) {
        vToast.warning("请输入客服电话");
        return;
      }
      
      if (!formData.value.icp_info) {
        vToast.warning("请输入ICP备案信息");
        return;
      }
      
      if (!formData.value.copyright) {
        vToast.warning("请输入版权信息");
        return;
      }
    }

    const res = await post("/setting/update", formData.value);

    if (res.code === 200) {
      vToast.success("网站设置更新成功");
    } else {
      vToast.error(res.msg || "更新失败");
    }
  } catch (error) {
    vToast.error("提交失败");
    console.error(error);
  }
};

// 初始化加载数据
onMounted(() => {
  fetchSettings();
  updateIndicatorPosition();
});

// 组件卸载时销毁编辑器
onUnmounted(() => {
  if (editorInstance.value) {
    editorInstance.value.destroy();
    editorInstance.value = null;
  }
});
</script>

<style scoped lang="less">
.site-setting-page {
  .breadcrumb {
    margin-bottom: 20px;
    
    .list {
      display: flex;
      align-items: center;
      font-size: 14px;
      
      .home-icon {
        margin-right: 8px;
        color: #999;
      }
      
      .item {
        margin-right: 8px;
        
        .text {
          color: #333;
          
          &:hover {
            color: var(--v-theme);
          }
        }
      }
      
      .seperate {
        margin-right: 8px;
        color: #999;
      }
    }
    
    .page-title {
      margin-top: 10px;
      font-size: 24px;
      font-weight: 500;
      color: #333;
    }
  }
  
  .tab-container {
    position: relative;
    margin-bottom: 20px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
    padding: 0 20px;
    
    .tabs {
      display: flex;
      
      .tab-item {
        padding: 16px 24px;
        cursor: pointer;
        font-size: 16px;
        font-weight: 500;
        color: #666;
        transition: all 0.3s ease;
        position: relative;
        z-index: 2;
        
        &:hover {
          color: var(--v-theme);
        }
        
        &.active {
          color: var(--v-theme);
        }
      }
    }
    
    .tab-indicator {
      position: absolute;
      bottom: 0;
      left: 0;
      height: 3px;
      background-color: var(--v-theme);
      transition: all 0.3s ease;
      z-index: 1;
    }
  }

  .form-container {
    width: 100%;
    padding: 20px;
  }

  .v-card {
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
    background: #fff;
    
    .card-header {
      padding: 16px 20px;
      border-bottom: 1px solid #eee;
      background: #f8f9fa;
      
      h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 500;
        color: #333;
      }
    }
    
    .card-body {
      padding: 20px;
    }
  }

  .form-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20px;
    
    .form-group {
      margin-bottom: 15px;
      
      .form-label {
        display: block;
        margin-bottom: 8px;
        font-size: 14px;
        color: #333;
        font-weight: 500;
      }
      
      .form-input {
        width: 100%;
        padding: 10px 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
        font-size: 14px;
        transition: border-color 0.3s;
        
        &:focus {
          border-color: var(--v-theme);
          outline: none;
        }
      }
      
      .form-hint {
        margin-top: 8px;
        font-size: 12px;
        color: #999;
      }
    }
  }
  
  .text-form-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
    
    .form-group {
      margin-bottom: 20px;
      
      &.full-width {
        grid-column: span 2;
      }
      
      .form-label {
        display: block;
        margin-bottom: 8px;
        font-size: 14px;
        color: #333;
        font-weight: 500;
      }
      
      .form-textarea {
        width: 100%;
        height: 120px;
        padding: 10px 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
        font-size: 14px;
        resize: vertical;
        transition: border-color 0.3s;
        
        &:focus {
          border-color: var(--v-theme);
          outline: none;
        }
      }
    }
  }

  .form-actions {
    display: flex;
    justify-content: center;
    margin-top: 30px;
    padding-top: 20px;
    border-top: 1px solid #eee;
    
    .v-button {
      min-width: 120px;
      height: 40px;
      padding: 0 20px;
      border-radius: 4px;
      font-size: 14px;
      cursor: pointer;
      
      &.primary {
        background-color: var(--v-theme);
        color: white;
        border: none;
        
        &:hover {
          background-color: var(--v-sidebar-background);
        }
      }
    }
  }
}
</style>